from matplotlib.pyplot import get
import pygame, sys, random
from pygame.locals import *
from sqlalchemy import false
from MCTS import MCTS_Player
from time import time
from AlphaBeta import Alphabeta_Player
from greedy import greedy_player
from util import *
 
BACKGROUNDCOLOR = (255, 255, 255)
BLACK = (255, 255, 255)
BLUE = (0, 0, 255)
CELLWIDTH = 50
CELLHEIGHT = 50
PIECEWIDTH = 47
PIECEHEIGHT = 47
BOARDX = 0
BOARDY = 0
FPS = 40


 
# 退出
def terminate():
    pygame.quit()
    sys.exit()
 
 
# 重置棋盘
def resetBoard(board):
    for x in range(8):
        for y in range(8):
            board[x][y] = 'none'
 
    # Starting pieces:
    board[3][3] = 'black'
    board[3][4] = 'white'
    board[4][3] = 'white'
    board[4][4] = 'black'
 
 
# 谁先走
def whoGoesFirst():
    if random.randint(0, 1) == 0:
        return 'computer'
    else:
        return 'player'
 
 
# 电脑走法，AI
def getComputerMove(board, computerTile):
    # 获取所以合法走法
    start = time()
    ai_pos = ai.NextPosition(board)
    end = time()
    one_time = end - start
    print("Step time:",format(one_time, '.4f'),"s")
    print(ai_pos)
    return [ai_pos[0], ai_pos[1]]
 
# 是否游戏结束
def isGameOver(board):
    if(getValidMoves(mainBoard, computerTile) == [] and getValidMoves(mainBoard, playerTile) == []):
        return True
    for x in range(8):
        for y in range(8):
            if board[x][y] == 'none':
                return False
    return True

 
if __name__ == "__main__":
    # 初始化
    pygame.init()
    mainClock = pygame.time.Clock()
    
    # 加载图片
    boardImage = pygame.image.load('img/board.png')
    boardRect = boardImage.get_rect()
    blackImage = pygame.image.load('img/black.png')
    blackRect = blackImage.get_rect()
    whiteImage = pygame.image.load('img/white.png')
    whiteRect = whiteImage.get_rect()
    validImage = pygame.image.load('img/red.png')
    validRect = validImage.get_rect()
    
    basicFont = pygame.font.SysFont('arial', 48)
    
    mainBoard = getNewBoard()
    resetBoard(mainBoard)
    
    turn = whoGoesFirst()
    if turn == 'player':
        playerTile = 'black'
        computerTile = 'white'
    else:
        playerTile = 'white'
        computerTile = 'black'
    

    mode = int(input('请选择你想对战的AI\n1. 蒙特卡洛树搜索\n2. AlphaBeta剪枝\n3. 贪心算法\n请输入：'))
    assert(mode == 1 or mode == 2 or mode == 3)
    if(mode == 1):
        think_time = float(input('请输入ai思考时间限制, 单位是秒:'))
        assert think_time > 0
        ai = MCTS_Player(turn, max_think_time=think_time)
    elif(mode == 2):
        maxdepth = int(input('请输入最大搜索深度，推荐6：'))
        assert maxdepth >= 1 and maxdepth <= 32
        ai = Alphabeta_Player(turn, maxdepth=maxdepth)
    else:
        ai = greedy_player(turn)
    
    print(turn + ' first') 
    
    # 设置窗口
    windowSurface = pygame.display.set_mode((boardRect.width, boardRect.height))
    pygame.display.set_caption('黑白棋')
    
    
    gameOver = False
    
    validMoveList = []
    savex, savey = 3, 3
    
    # 游戏主循环
    while True:
        #player's turn
        if turn == 'player':
            windowSurface.fill(BACKGROUNDCOLOR)
            windowSurface.blit(boardImage, boardRect, boardRect)
            validMoveList = getValidMoves(mainBoard, playerTile)
            for validMoveXY in validMoveList:
                x = validMoveXY[0]
                y = validMoveXY[1]
                rectDst = pygame.Rect(BOARDX+x*CELLWIDTH+2, BOARDY+y*CELLHEIGHT+2, PIECEWIDTH, PIECEHEIGHT)
                windowSurface.blit(validImage, rectDst, validRect)
            
            
            for event in pygame.event.get():
                if event.type == QUIT:
                    terminate()
                if gameOver == False and turn == 'player' and event.type == MOUSEBUTTONDOWN and event.button == 1:
                    x, y = pygame.mouse.get_pos()
                    col = int((x-BOARDX)/CELLWIDTH)
                    row = int((y-BOARDY)/CELLHEIGHT)
                    if makeMove(mainBoard, playerTile, col, row) == True:
                        if validMoveList != []:
                            turn = 'computer'

            for x in range(8):
                for y in range(8):
                    rectDst = pygame.Rect(BOARDX+x*CELLWIDTH+2, BOARDY+y*CELLHEIGHT+2, PIECEWIDTH, PIECEHEIGHT)
                    if mainBoard[x][y] == 'black':
                        windowSurface.blit(blackImage, rectDst, blackRect)
                    elif mainBoard[x][y] == 'white':
                        windowSurface.blit(whiteImage, rectDst, whiteRect)

            rectDst = pygame.Rect(BOARDX+savex*CELLWIDTH+2, BOARDY+savey*CELLHEIGHT+2, PIECEWIDTH, PIECEHEIGHT)
            windowSurface.blit(validImage, rectDst, validRect)
            pygame.display.update()

        #computer's turn
        if turn == 'computer':
            windowSurface.fill(BACKGROUNDCOLOR)
            windowSurface.blit(boardImage, boardRect, boardRect)
            validMoveList = getValidMoves(mainBoard, computerTile)
            for validMoveXY in validMoveList:
                x = validMoveXY[0]
                y = validMoveXY[1]
                rectDst = pygame.Rect(BOARDX+x*CELLWIDTH+2, BOARDY+y*CELLHEIGHT+2, PIECEWIDTH, PIECEHEIGHT)
                windowSurface.blit(validImage, rectDst, validRect)
            
            for x in range(8):
                for y in range(8):
                    rectDst = pygame.Rect(BOARDX+x*CELLWIDTH+2, BOARDY+y*CELLHEIGHT+2, PIECEWIDTH, PIECEHEIGHT)
                    if mainBoard[x][y] == 'black':
                        windowSurface.blit(blackImage, rectDst, blackRect)
                    elif mainBoard[x][y] == 'white':
                        windowSurface.blit(whiteImage, rectDst, whiteRect)
            pygame.display.update()

            if (gameOver == False and turn == 'computer'):
                if(getValidMoves(mainBoard, computerTile) != []):
                    pygame.time.wait(200)
                    x, y = getComputerMove(mainBoard, computerTile)
                    makeMove(mainBoard, computerTile, x, y)
                    savex, savey = x, y
        
                # 玩家没有可行的走法了
                if getValidMoves(mainBoard, playerTile) != []:
                    turn = 'player'
        
            for x in range(8):
                for y in range(8):
                    rectDst = pygame.Rect(BOARDX+x*CELLWIDTH+2, BOARDY+y*CELLHEIGHT+2, PIECEWIDTH, PIECEHEIGHT)
                    if mainBoard[x][y] == 'black':
                        windowSurface.blit(blackImage, rectDst, blackRect)
                    elif mainBoard[x][y] == 'white':
                        windowSurface.blit(whiteImage, rectDst, whiteRect)

            pygame.display.update()
    
        if isGameOver(mainBoard):
            turn = 'null'
            scorePlayer = getScoreOfBoard(mainBoard)[playerTile]
            scoreComputer = getScoreOfBoard(mainBoard)[computerTile]
            if scorePlayer > scoreComputer:
                gameoverStr = 'Player win'
            elif scorePlayer < scoreComputer:
                gameoverStr = 'Computer win'
            else:
                gameoverStr = 'Draw'
            outputStr = gameoverStr + str(scorePlayer) + ":" + str(scoreComputer)
            text = basicFont.render(outputStr, True, BLACK, BLUE)
            textRect = text.get_rect()
            textRect.centerx = windowSurface.get_rect().centerx
            textRect.centery = windowSurface.get_rect().centery
            windowSurface.blit(text, textRect)
            pygame.display.update()
            for event in pygame.event.get():
                if event.type == QUIT:
                    terminate()

        mainClock.tick(FPS)